import {
  Breadcrumb,
  Radio,
  Card,
  Form,
  Button,
  DatePicker,
  Table,
  Tag,
  Avatar,
  Space,
  Modal,
  message,
} from 'antd';
import error from 'assets/error.png';
import styles from './index.module.scss';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { getarticles, delarticles } from 'api/list';
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import Channel from 'components/Channel';
const { RangePicker } = DatePicker;
export default function ArticleList(props) {
  const [articles, setArticles] = useState([]);
  const paramsRef = useRef();
  //获取文章列表以及列表总数
  async function getarticlesList(params) {
    const { data } = await getarticles(params);
    setArticles(data);
  }

  useEffect(() => {
    getarticlesList();
  }, []);

  //提交事件
  const onFinish = async (values) => {
    let data = { ...values };
    if (data.status === -1) delete data.status;
    if (data.date) {
      data.begin_pubdate = data.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      data.end_pubdate = data.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      delete data.date;
    }
    data = JSON.parse(JSON.stringify(data));
    await getarticlesList(data);
    paramsRef.current = data;
  };

  //切换分页事件
  function onShowSizeChange(page, per_page) {
    const params = paramsRef.current || {};
    getarticlesList({ ...params, page, per_page });
  }

  //删除事件
  const handleDelItem = (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除这篇文章？',
      onOk: async () => {
        await delarticles(id);
        message.success('删除文章成功!');
        const params = paramsRef.current || {};
        let { page, per_page } = articles;
        if (articles.results.length <= 1) page -= 1;
        getarticlesList({ ...params, page, per_page });
      },
    });
  };

  //tag枚举数据
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  //Table列表头格式数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      render: (cover) => {
        let SrcImg = cover.images.length ? cover.images[0] : error;
        return <Avatar shape="square" size={64} src={SrcImg} />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      onCell: () => {
        return {
          style: {
            maxWidth: 150,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        let statusinfo = articleStatus.find((item) => item.id === status);
        return <Tag color={statusinfo.color}>{statusinfo.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (value, record) => {
        return (
          <Space>
            <Button
              icon={<EditOutlined />}
              type="primary"
              data-id={record.id}
              shape="circle"
              onClick={() => props.history.push(`/edit/${record.id}`)}
            ></Button>
            <Button
              icon={<DeleteOutlined />}
              danger
              shape="circle"
              onClick={() => handleDelItem(record.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];

  return (
    <Card
      title={
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/home">首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>文章列表</Breadcrumb.Item>
        </Breadcrumb>
      }
      bordered={false}
    >
      <Form
        initialValues={{
          status: -1,
          channel_id: 0,
        }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item label="状态" name="status">
          <Radio.Group>
            <Radio value={-1}>全部</Radio>
            <Radio value={0}>草稿</Radio>
            <Radio value={1}>待审核</Radio>
            <Radio value={2}>审核通过</Radio>
            <Radio value={3}>审核失败</Radio>
          </Radio.Group>
        </Form.Item>

        <Channel></Channel>

        <Form.Item name="date" label="日期">
          <RangePicker />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>

      <p>根据筛选条件共查询到 {articles.total_count} 条结果：</p>

      <Table
        className={styles.center_table}
        rowKey="id"
        columns={columns}
        dataSource={articles.results}
        pagination={{
          current: articles.page,
          showSizeChanger: true,
          onChange: onShowSizeChange,
          pageSize: articles.per_page,
          total: articles.total_count,
        }}
      />
    </Card>
  );
}
